<script setup>
import {useUserStore} from '@/stores/user'
import ButtonX from '@/components/button-x/index.vue'
import IconSimple from '@/components/icon-simple/index.vue'
import UniPopup from '@dcloudio/uni-ui/lib/uni-popup/uni-popup.vue'
import {usePopup} from '@/hooks/usePopup'
import to from 'await-to-js'
import {login} from '@/utils/uni-api-wrap/sys'
import {tip} from '@/utils/uni-api-wrap/toast'

const emit = defineEmits(['loginSuccess'])

const userStore = useUserStore()

const { popup, close, open } = usePopup()

const check = () => {
  // 未登录，弹出授权登录框
  if (!userStore.token) {
    // nextTick(() => open())
    loginAction()
  } else {
    nextTick(() => close())
  }
}

onUpdated(() => check())
onMounted(() => check())

const getphonenumber = ({ detail: { code, encryptedData, iv } }) => {
  userStore.loginAction({ code, encryptedData, iv })
}

const loginAction = () => userStore.loginAction()

watch(() => userStore.token, newToken => {
  if (newToken) emit('loginSuccess', newToken)
})

</script>

<template>
  <view class="access-intercept__container" :class="{ 'access-intercept--isNoLogin': !userStore.token }">
    <slot></slot>
    <uni-popup ref="popup" type="bottom" :safe-area="false" :is-mask-click="false">
      <template #default>
        <view class="access-intercept__popupContainer flex-row">
          <view class="notlogin__tip">还未登录，请登录</view>
          <view class="login-button__container">
            <button-x open-type="click" size="small" type="warn" mode="round" @click="loginAction">登录</button-x>
          </view>
        </view>
      </template>
    </uni-popup>
  </view>
</template>

<style scoped lang="scss">
.access-intercept__container {
  position: relative;
}
.access-intercept--isNoLogin {
  &::after {
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
  }
}
.access-intercept__popupContainer {
  border-radius: 20rpx 20rpx 0 0;
  padding: 32rpx;
  background-color: #fff;
  overflow: hidden;
}
.notlogin__tip {
  flex: 2;
}
.login-button__container {
  flex: 1;
}
</style>
